﻿// (c) Comkarl Calipso
// By Matías Fidemraizer (http://www.matiasfidemraizer.com)
// -------------------------------------------------
// http://calipso.codeplex.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Comkarl.Web.Configuration;
using Comkarl.Web.UI;
using System;
using System.Linq;
using System.Web;

namespace Comkarl.Web
{
    public sealed class CalipsoHttpModule : IHttpModule
    {
        private readonly static object _lock = new object();
        private volatile static bool _started;

        private bool Started
        {
            get
            {
                return _started;
            }
            set
            {
                _started = value;
            }
        }

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            lock (_lock)
            {
                if (!Started)
                {
                    new JavaScriptManager().Start();
                    new CssManager().Start();

                    Started = true;
                }
            }

            context.BeginRequest += HttpApplication_BeginRequest;
        }

        private void HttpApplication_BeginRequest(object sender, EventArgs e)
        {
            string themeId = null;

            if (HttpContext.Current.Request.Cookies.AllKeys.Contains(CalipsoSection.Current.CssManager.Theming.ThemeCookieName))
            {
                themeId = HttpContext.Current.Request.Cookies[CalipsoSection.Current.CssManager.Theming.ThemeCookieName].Value;
            }
            else
            {
                themeId = CalipsoSection.Current.CssManager.Theming.Themes.DefaultThemeId;
            }

            CssManager.CurrentThemeId = themeId;
        }
    }
}